package com.xzg.user.service;

import com.xzg.common.constants.Constant;
import com.xzg.common.page.PageQueryBean;
import com.xzg.common.resp.APIResult;
import com.xzg.common.utils.MD5Utils;
import com.xzg.common.vo.QueryCondition;
import com.xzg.middleTable.dao.LabelMapper;
import com.xzg.middleTable.dao.LabelUserMapper;
import com.xzg.middleTable.entity.Label;
import com.xzg.middleTable.entity.LabelUser;
import com.xzg.user.dao.UserMapper;
import com.xzg.user.entity.User;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Service("UserServiceImpl")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private LabelUserMapper labelUserMapper;


/**
 *@Author Ye
 *Date 2018-03-02 15:31
 *@Description 创建用户
 */
    @Override
    public void creatUser(User user) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        user.setPassword(MD5Utils.encrptyPassword(user.getPassword()));
        userMapper.insert(user);
    }

    /**
     *@Author Ye
     *Date 2018-03-05 9:48
     *@Description 根据用户名查询所有用户
     */
    @Override
    public User findUserByusername(String username) {
        User user = null;
        try{
            user = userMapper.selectByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        return user;
    }

    /**
     *@Author Ye
     *Date 2018-03-05 9:48
     *@Description 查询所有用户
     */
    @Override
    public PageQueryBean findAllUser(QueryCondition condition) {
        int count = userMapper.countUser();
        PageQueryBean pageResult = new PageQueryBean();
        if(count>0){
            pageResult.setTotalRows(count);
            pageResult.setCurrentPage(condition.getCurrentPage());
            pageResult.setPageSize(condition.getPageSize());
            List<User> userlist = userMapper.listUser(condition);
            pageResult.setItems(userlist);
        }
        return pageResult;
    }

    @Override
    public User checkCid(User user) {
        String cid = (String) SecurityUtils.getSubject().getSession().getAttribute("cid");
            if(user.getCID()==null||user.getCID()!=cid) {
                user.setCID(cid);
                userMapper.updateByPrimaryKeySelective(user);
            }
            user = userMapper.selectIntegral(user.getId());
            SecurityUtils.getSubject().getSession().setAttribute("userinfo",user);
            return user;
    }

    @Override
    public User selectALLByUsername(String username) {
        User user = userMapper.selectAllByUsername(username);
        return user;
    }

    @Override
    public int updateUser(User user) {
        int i = 0;
        try{
            User Currentuser = (User) SecurityUtils.getSubject().getSession().getAttribute("userinfo");
            Currentuser.setNickName(user.getNickName());
            userMapper.updateByPrimaryKeySelective(Currentuser);
            i = 1;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    @Override
    public APIResult checklabel(User user) {
        APIResult resp = new APIResult();
        user = userMapper.selectIntegral(user.getId());
        SecurityUtils.getSubject().getSession().setAttribute("userinfo",user);
        List<Label> label = labelMapper.selectall();
        resp.setData(user);
        resp.setData2(label);
        return resp;
    }
    @Override
    @Transactional
    public APIResult insertLabel(Label label) {
        APIResult resp = new APIResult();
        if(label!=null) {
            labelMapper.insertSelective(label);
            resp.setMessage("添加成功");
        }
        return resp;
    }
    @Override
    public APIResult updateLabelUser(QueryCondition condition) {
        APIResult resp = new APIResult();
        if(condition.getLabelName()!=null&&condition.getLabelName()!="") {
//            JSONObject jsonObj = JSONObject.fromObject(condition.getLabelName());
//            String labelName = jsonObj.getString("labelName");
            String[] split = condition.getLabelName().split(",");
            if(split!=null) {
                List<Label> labels = new ArrayList<>();
                for (int i = 0 ; i<split.length;i++) {
                    Label label = new Label();
                    label.setLabelName(split[i]);
                    labels.add(label);
                }
                List<Label> labelList = labelMapper.selectByName(labels);
                List<LabelUser> labelUsers = new ArrayList<>();
                for (Label label : labelList) {
                    LabelUser labelUser = new LabelUser();
                    labelUser.setLabelLid(label.getLabelId());
                    labelUser.setLabelUid(condition.getId());
                    labelUsers.add(labelUser);
                }
                labelUserMapper.batchInsert(labelUsers);
            }
            resp.setMessage("修改成功");
        }
        return resp;
    }
    @Override
    public APIResult deleteLabel(QueryCondition condition) {
        APIResult resp = new APIResult();
        try{
            if(condition.getId()!=null) {
                if (condition.getLabelName()!=null&&condition.getLabelName()!=""){
                    Label label = labelMapper.selectByNames(condition.getLabelName());
                    LabelUser labelUser = new LabelUser();
                    labelUser.setLabelLid(label.getLabelId());
                    labelUser.setLabelUid(condition.getId());
                    labelUserMapper.deleteByLid(labelUser);
                    resp.setMessage("删除成功");
                } else {
                    labelMapper.deleteByPrimaryKey(condition.getLabelId());
                    resp.setMessage("删除成功");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("删除失败");
        }
        return resp;
    }

    /**
     * @Author: ye
     * @Date: 16:05 2018\4\10 0010
     * @Description 查看所有标签
     */
    @Override
    public APIResult allLabel() {
        APIResult resp = new APIResult();
        try{
            List<Label> label = labelMapper.selectall();
            resp.setData(label);
            resp.setMessage("查询成功");
        }catch (Exception e) {
            e.printStackTrace();
            resp.setMessage("查询失败");
            resp.setCode(Constant.RESP_STATUS_INTERNAL_ERROR);
        }
        return resp;
    }


}
